const { build, defineConfig } = require('vite');
// 用到的插件
const vue = require('@vitejs/plugin-vue');
const vueJsx = require('@vitejs/plugin-vue-jsx');
// const css = require('vite-plugin-css');
const terser = require('rollup-plugin-terser').terser;
const path = require('path');
const fs = require('fs');
const compressing = require('compressing');
const pipe = require('multipipe');
const AutoImport = require('unplugin-auto-import/vite').default;
const Components = require('unplugin-vue-components/vite').default;
const { ElementPlusResolver } = require('unplugin-vue-components/resolvers');

const packageConfig = require('../packages/config/package-base-info.cjs');
const resolve = (pathUrl) => {
	return path.resolve(__dirname, pathUrl);
};

const pkgConfig = {
	name: packageConfig.moduleName,
	version: packageConfig.version,
	nameVersion: packageConfig.moduleName + '/' + packageConfig.version,
	type: packageConfig.cpntType,
	versionDesc: packageConfig.versionDesc, //版本描述
	description: packageConfig.description,
};
const pkg = `${pkgConfig.name}_${pkgConfig.version}`;

const baseConfig = defineConfig({
	mode: 'production',
	resolve: {
		alias: {
			'@': resolve('../src'), // 相对路径别名配置，使用 @ 代替 src
			'@CIF': resolve('../src/views/CIF'),
			'@packages': resolve('../packages')
		}
	},
	// publicDir: resolve('../packages/assets'),
	plugins: [
		vue(),
		vueJsx(),
		terser({
			compress: {
				global_defs: {
					'process.env.NODE_ENV': 'production'
				}
			}
		}),
		// css({ output: 'styles--s.css' }),
		AutoImport({
			resolvers: [ElementPlusResolver()]
		}),
		Components({
			resolvers: [ElementPlusResolver()]
		})
	],
	build: {
		target: 'modules',
		inlineDynamicImports: false,
		emptyOutDir: true,
		lib: {
			formats: ['umd', 'iife'], // 确保是iife格式 iife的格式才会挂载到全局变量
			entry: '../src/views/CIF/ComponentPackager/entry.js',
			name: `${pkg}`,
			fileName: (format) => `${pkg}.${format}.js`
		},
		outDir: resolve('../pkgDist'),
		rollupOptions: {
			// plugins: [css({ output: `${pkg}.css` })],
			// 确保外部化处理那些你不想打包进库的依赖
			external: ['vue', 'Color'],
			input: '../src/views/CIF/ComponentPackager/entry.js',
			output: {
				name: `${pkg}`,
				format: 'umd',
				entryFileNames: `${pkg}.umd.js`,
				chunkFileNames: `${pkg}.umd.js`,
				// assetFileNames: `cif_assets/${pkgConfig.name}/${pkgConfig.version}/img/[name].[ext]`,
				assetFileNames: (assetInfo) => {
					let info = assetInfo.name.split('.');
					let extType = info[info.length - 1];
					if (/\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/i.test(assetInfo.name)) {
						extType = 'media';
					} else if (/\.(png|jpe?g|gif|svg)(\?.*)?$/.test(assetInfo.name)) {
						extType = 'img';
					} else if (/\.(woff2?|eot|ttf|otf)(\?.*)?$/i.test(assetInfo.name)) {
						extType = 'fonts';
					} else if (/\.(css?|less|sass|scss)(\?.*)?$/i.test(assetInfo.name)) {
						extType = 'css';
						return `${pkg}.css`;
					}
					return `assets/${pkgConfig.name}/${pkgConfig.version}/${extType}/[name][extname]`;
				},
				// // 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
				globals: {
					vue: 'Vue',
					Color: 'Color'
				},
				preserveEntrySignatures: 'strict',
				inlineDynamicImports: false
			}
		}
	}
});

async function main() {
	await build(baseConfig);
	let withAssets = false;
	// let assetsFilePath = []
	try {
		fs.accessSync('../pkgDist/assets', fs.constants.R_OK | fs.constants.W_OK);
		console.log('CIF.CP.buildPkg:exec 发现静态资源');
		withAssets = true;
		// assetsFilePath = fs.readdirSync("builtPkg/img");
	} catch (err) {
		console.log('CIF.CP.buildPkg:exec 未发现静态资源');
	}

	//把data对象转换为json格式字符串
	const content = JSON.stringify({
		name: pkgConfig.name,
		version: pkgConfig.version,
		type: pkgConfig.type,
		versionDesc: pkgConfig.versionDesc, //版本描述
		description: pkgConfig.description,
		withAssets: withAssets
	});
	//指定创建目录及文件名称，__dirname为执行当前js文件的目录 ../../../builtPkg/baseinfo.json
	const file = resolve('../pkgDist/baseinfo.json');

	//写入文件
	fs.writeFile(file, content, 'utf-8', function (err) {
		if (err) {
			console.log('CIF.CP.buildPkg:exec 配置文件创建失败 ', err);
		}
		console.log('CIF.CP.buildPkg:exec 配置文件创建成功，地址：', file);

		// 检查文件是否存在于当前目录中。
		fs.access(file, fs.constants.F_OK, (err) => {
			console.log(`${file} ${err ? '不存在' : '存在'}`);
		});

		const tarStream = new compressing.zip.Stream();
		// file
		tarStream.addEntry(`../pkgDist/${pkg}.css`);
		tarStream.addEntry(`../pkgDist/${pkg}.umd.js`);
		tarStream.addEntry('../pkgDist/baseinfo.json');

		if (withAssets) {
			tarStream.addEntry('../pkgDist/assets');
		}

		const destStream = fs.createWriteStream(`../pkgDist/${pkg}.zip`);
		pipe(tarStream, destStream, (err) => {
			if (err) console.log(err);
		});
	});
}

main();
